<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!--      slot="detail"-->
      <div class="container">
        <a-form>
          <table border="1" cellspacing="0" cellpadding="0">
            <tr style="height: 40px" class="title_tr no_border">
              <td class="no_border"><img src="@/assets/aee_execl.png" style="height: 40px"></td>
              <td colspan="10" style="text-align: center ;font-size: larger" class="no_border">{{ model.year }} 年
                {{ model.month }} 月份工作目标与绩效管理
              </td>
            </tr>
            <tr style="height: 40px" class="no_border">
              <td class="no_border text_right">中心：</td>
              <td class="no_border" :contenteditable="selfEditAble" v-html="model.centerPart "
                  @blur="model.centerPart =$event.target.innerText">
              </td>
              <td class="no_border text_right">部门：</td>
              <td class="no_border" :contenteditable="selfEditAble" v-html="model.department "
                  @blur="model.department =$event.target.innerText">
              </td>
              <!--              <td class="no_border">{{ model.department }}</td>-->
              <td class="no_border text_right">职务：</td>
              <td class="no_border" colspan="3" :contenteditable="selfEditAble" v-html="model.post "
                  @blur="model.post =$event.target.innerText">
              </td>
              <td class="no_border text_right">姓名：</td>
              <td class="no_border" colspan="3" :contenteditable="selfEditAble" v-html="model.realname "
                  @blur="model.realname =$event.target.innerText">
              </td>
            </tr>
            <tr>
              <th>类别</th>
              <th>序号</th>
              <th colspan="2">重点工作内容</th>
              <th colspan="3" style="width: 400px">结果评价及验收标准</th>
              <th>考核分值</th>
              <th>自评分</th>
              <th>上级评分</th>
              <th class="center_backgroud">中心领导</th>
            </tr>

            <tr v-for="(item,index) in model.worktaskList" :key="index">

              <th v-if="index==0" :rowspan="model.worktaskList.length" style="color: red">
                <a-popover title="操作" v-if="selfEditAble">
                  <template #content>
                    <a-button block @click="addLineImport()">添加一行</a-button>
                  </template>
                  <span>  一、工作任务(权重30%)</span>
                </a-popover>
                <span v-else> 一、工作任务(权重30%)</span>
              </th>
              <td>
                <a-popover title="操作" v-if="selfEditAble">
                  <template #content>
                    <a-button danger block @click="deleteImport(index)">删除</a-button>
                    <!--                    <a-button block @click="addLineImport()">添加一行</a-button>-->
                  </template>
                  <span> {{ item.index }}</span>
                </a-popover>
                <span v-else> {{ item.index }}</span>
              </td>
              <td class="important_tr" colspan="2" :contenteditable="selfEditAble" v-html="item.workContent"
                  @blur="item.workContent=$event.target.innerText">
              </td>
              <td colspan="3" :contenteditable="selfEditAble" v-html="item.checkMethod"
                  @blur="item.checkMethod=$event.target.innerText">
              </td>
              <td>0或10</td>
              <td :contenteditable="selfEditAble" v-html="item.selfScore"
                  @blur="blurNumFunc($event,1,index,'selfScore')">
                <!--            <a-input-number :min="0" :max="10" :step="10"/>-->
              </td>
              <td :contenteditable="superiorEditAble" v-html="item.superiorScore"
                  @blur="blurNumFunc($event,1,index,'superiorScore')">
                <!--            <a-input-number :min="0" :max="10" :step="10"/>-->
              </td>
              <td :contenteditable="centerEditAble" v-html="item.centerScore" class="center_backgroud"
                  @blur="blurNumFunc($event,1,index,'centerScore')">
                <!--            <a-input-number :min="0" :max="10" :step="10"/>-->
              </td>
            </tr>
            <tr>
              <th :rowspan="model.aeeKpiAssessments.length+3" style="color: red">
                <a-popover title="操作" v-if="selfEditAble">
                  <template #content>
                    <a-button block @click="addLineAssess()">添加一行</a-button>
                  </template>
                  <span> 二、月考核指标(权重90%)</span>
                </a-popover>
                <span v-else> 二、月考核指标(权重90%)</span>
              </th>
            </tr>
            <tr>
              <th>方式</th>
              <th>KPI指标</th>
              <th>指标定义</th>
              <th>权重</th>
              <th colspan="3">考核目标值及计分方式</th>
              <th>自评分</th>
              <th>上级评分</th>
              <th class="center_backgroud">中心领导</th>
            </tr>
            <tr style="background: yellow">
              <td :rowspan="model.aeeKpiAssessments.length+1" style="background: white">
                KPI考核
              </td>
              <td>根据部门岗位定考核指标</td>
              <td>根据KPI指标定义</td>
              <td>根据KPI指定标权重比率</td>
              <td colspan="3">根据KPI指标目标值列出考核达成率，上限计分不超权重的20%</td>
              <td></td>
              <td></td>
              <td class="center_backgroud"></td>
            </tr>
            <tr v-for="(item,index) in model.aeeKpiAssessments " :key="'aeeKpiAssessments'+index">
              <a-dropdown v-if="selfEditAble" :trigger="['contextmenu']">
                <!--                <a class="ant-dropdown-link" @click.prevent>-->
                <!--                  Hover me, Click menu item-->
                <td class="assessment_tr" :contenteditable="selfEditAble" v-html="item.kpiAssessment"
                    @blur="item.kpiAssessment=$event.target.innerText;">
                  <DownOutlined/>
                </td>
                <!--                </a>-->
                <template #overlay>
                  <a-menu @click="onDeleteClick($event.key,index)">
                    <a-menu-item key="1">删除当前行</a-menu-item>
                    <a-menu-item key="2">向下插入一行</a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>

              <td class="assessment_tr" v-else>
                {{ item.kpiAssessment }}
              </td>
              <td :contenteditable="selfEditAble" v-html="item.assessmentDefine"
                  @blur="item.assessmentDefine=$event.target.innerText"></td>
              <td :contenteditable="selfEditAble" v-html="item.assessWeight"
                  @blur="item.assessWeight=$event.target.innerText"></td>
              <td colspan="3" align="left" :contenteditable="selfEditAble" v-html="item.targetValue"
                  @blur="item.targetValue=$event.target.innerText">
                <!--            A，积极加入苍穹项目，积极参与项目会议及需求分析<br/>-->
                <!--            B，积极加入，主动分析难点，积极讨论<br/>-->
                <!--            C，消极抵制，无理逃避-->
              </td>
              <td :contenteditable="selfEditAble" v-html="item.selfScore" @blur="blurNumFunc($event,2,index,'selfScore')
          ">
                <!--            <a-input-number :min="0" :max="10" :step="10"/>-->
              </td>
              <td :contenteditable="superiorEditAble" v-html="item.superiorScore"
                  @blur="blurNumFunc($event,2,index,'superiorScore')">
                <!--            <a-input-number :min="0" :max="10" :step="10"/>-->
              </td>
              <td :contenteditable="centerEditAble" v-html="item.centerScore" class="center_backgroud"
                  @blur="blurNumFunc($event,2,index,'centerScore')">
                <!--            <a-input-number :min="0" :max="10" :step="10"/>-->
              </td>
            </tr>
            <tr>
              <td colspan="8">总合计分数</td>
              <td>{{ lastSelfScore }}</td>
              <td>{{ lastSuperiorScore }}</td>
              <td class="center_backgroud">{{ lastCenterScore }}</td>
            </tr>
            <tr>
              <th rowspan="4">三、结果评价</th>
              <th colspan="1">个人资源需求说明</th>
              <td colspan="5" align="left" :contenteditable="selfEditAble" v-html="model.resultAssess.requirements"
                  @blur="model.resultAssess.requirements=$event.target.innerText"></td>
              <td>被考核人签名</td>
              <!--          本人签名-->
              <td colspan="3"></td>
            </tr>
            <tr class="center_backgroud">
              <th colspan="1">上级评价</th>
              <td colspan="5" align="left" :contenteditable="superiorEditAble" v-html="model.resultAssess.superAssess"
                  @blur="model.resultAssess.superAssess=$event.target.innerText">肯定项/改进项说明:
              </td>
              <td>直接上级审批</td>
              <!--          上级签字-->
              <td colspan="3"></td>
            </tr>
            <tr class="center_backgroud">
              <th colspan="1">中心领导评价</th>
              <td colspan="5" align="left" :contenteditable="centerEditAble" v-html="model.resultAssess.centerAssess"
                  @blur="model.resultAssess.centerAssess=$event.target.innerText">肯定项/改进项说明：
              </td>
              <td>中心领导审批</td>
              <!--          上级中心领导签字-->
              <td colspan="3"></td>
            </tr>
            <tr>
              <th colspan="1">最终得分</th>
              <td colspan="5">绩效得分(直接上级评分)±绩效异常分±个人奖惩得分(人力资源部评分)</td>
              <td colspan="4" contenteditable="true" v-html="model.resultAssess.resultSocre"
                  @blur="model.resultAssess.resultSocre=$event.target.innerText"></td>
            </tr>
            <tr style="color: red">
              <th rowspan="6">四、绩效考核说明</th>
              <th colspan="10" rowspan="6" style="text-align: left">
                1、工作任务项每个月必须至少有三项重点工作，三项重点工作考核结果只有0分或10分（部门负责人不得打出1-9分）；<br/>
                2、员工当月绩效低于85分，将视为当月工作未能满足岗位要求；<br/>
                3、员工在连续十二个月内累积三个月绩效考核低于85分，公司将确定其本人不符合公司岗位要求，公司将给予调岗处理；当员工连续十二个月内累积两个月低于85分时部门负责人与人力资源部应及时找其谈话，提醒不断提高自身的工作能力，给予警示。<br/>
                4、各职能中心员工绩效分（按人员数量）等级占比为：A类110分-120分不超过5%：B类105分-109分不超过20%：C类100分-104分不超过60%；<br/>
                5、绩效确认生效，即发放工资完毕，如无异议则视为员工对本次绩效考核确认。如有异议，可以书面向上级申诉及简单说明申诉原因，申诉成功后，由员工本人再签字确认。<br/>
              </th>
            </tr>
          </table>
        </a-form>
      </div>
    </j-form-container>
  </a-spin>
</template>

<script>

import {httpAction, getAction} from '@/api/manage'
import {validateDuplicateValue} from '@/utils/util'
import moment from 'moment';
import JavaForm from './JavaForm'
import {mapGetters} from "vuex";

class Improtent {
  index;
  workContent;
  checkMethod;
  selfScore;
  superiorScore;
  centerScore;

  constructor(index) {
    this.index = index;
  }
}

class Assessments {
  index;
  kpiAssessment;
  assessmentDefine = "完成";
  assessWeight;
  targetValue;
  selfScore;
  superiorScore;
  centerScore;

  constructor(index) {
    this.index = index;
  }
}

export default {
  name: 'AeeKpiMainForm',
  components: {JavaForm},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {
        centerPart: "",
        department: '',
        post: '',
        realname: '',
        year: "",
        month: "",
        worktaskList: [],
        aeeKpiAssessments: [],
        resultAssess: {
          //个人需求说明
          requirements: "",
          //个人签名
          selfSign: "",
          //上级评价
          superAssess: "",
          //上级签名
          superSign: "",
          //中心评价
          centerAssess: '',
          //中心签名
          centerSign: "",
          //最后得分
          resultSocre: 0,

        },
      },
      lastSelfScore: "",
      lastSuperiorScore: "",
      lastCenterScore: "",
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: "/manage/aeeKpiMain/add",
        edit: "/manage/aeeKpiMain/edit",
        queryById: "/manage/aeeKpiMain/queryById",
        assessmentD: "/manage/aeeKpiMain/queryById"
      },
      //初始状态
      status: 0,
      //属于哪个用户的kpi
      userId: "",
      centerId: "",
      superiorId: "",
      isFlow: false,
      assignee:""


    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    //自己可编辑
    selfEditAble: function () {
      //当状态为初始状态的时候，或者为提交审批的时候可编辑
      return this.status == 0 && (this.userId == "" || this.userId == this.userInfo().id)&&!this.formDisabled;
    },
    superiorEditAble: function () {
      return true;
      // this.status == 1&& this.superiorId==this.userInfo().id && this.assignee==this.superiorId &&!this.formDisabled;
    },
    centerEditAble: function () {
      return true;
      // this.status == 1&& this.centerId==this.userInfo().id &&this.assignee==this.centerId&&!this.formDisabled;
    },
    // lastSelfScore:  {
    //   get(){
    //     return this.getLastScore('selfScore')
    //   },
    //   set(val){
    //
    //   }
    //
    //
    // },
    // lastSuperiorScore:  {
    //   get(){
    //     return this.getLastScore('superiorScore')
    //
    //   },
    //   set(val){
    //
    //   }
    //
    // },
    // lastCenterScore: {
    //   get(){
    //     return this.getLastScore('centerScore')
    //
    //   },
    //   set(val){
    //
    //   }

    // },
    // worktaskList() {
    //   return this.model.worktaskList;
    // },
    // aeeKpiAssessments() {
    //   return this.model.aeeKpiAssessments;
    // }

  },
  watch: {
    'model.worktaskList': {
      handler: function (val, oldVal) {
        // this.contents=val;
        console.log(val)
        this.lastSuperiorScore = this.getLastScore('superiorScore');
        this.lastSelfScore = this.getLastScore('selfScore')
        this.lastCenterScore = this.getLastScore('centerScore')
      },
      immediate: true,
      deep: true
    },

    'model.aeeKpiAssessments': {
      handler: function (val, oldVal) {
        // this.assessments=val;
        this.lastSuperiorScore = this.getLastScore('superiorScore');
        this.lastSelfScore = this.getLastScore('selfScore')
        this.lastCenterScore = this.getLastScore('centerScore')
      },
      immediate: true,
      deep: true
    },
  },
  created() {
    //备份model原始值
    // this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },

  methods: {

    add() {
      this.model.year = moment().format('YYYY');
      this.model.month = moment().format('MM');

      this.model.worktaskList = [
        new Improtent(1), new Improtent(2), new Improtent(3)
      ];
      this.model.centerPart = this.userInfo().centerPart;
      this.model.department = this.userInfo().orgCodeTxt;
      this.model.post = this.userInfo().post;
      this.model.realname = this.userInfo().realname;
      this.userId = this.userInfo().id;

      // this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // this.edit(this.modelDefault)
      this.visible = true
    },
    edit(record) {
      this.queryKpiByID(record.id)
      // this.model = Object.assign({}, record);
      this.visible = true;
    },
    examine(record) {
      this.isFlow = true;
      this.queryKpiByID(record.id)
      this.visible = true;
    },
    queryKpiByID(id) {
      this.confirmLoading = true;
      getAction(this.url.queryById, {id: id}).then((res) => {

        if (res.success) {
          var record = res.result;
          this.showKpi(record);
        }
        this.confirmLoading = false;
      })
    },
    showKpi(record) {
      this.model.id = record.id;
      this.model.year = record.year;
      this.model.month = record.month;
      this.status = record.status;
      this.userId = record.userId;
      this.centerId = record.centerId;
      //当前办理人
      this.assignee= record.assignee;
      this.superiorId = record.superiorId;
      this.model.worktaskList = record.worktaskList;
      this.model.aeeKpiAssessments = record.aeeKpiAssessments;
      this.model.centerPart = record.centerPart;
      this.model.department = record.department;
      this.model.post = record.post;
      this.model.realname = record.realname;
      this.model.resultAssess = record.resultAssess;
      this.lastSuperiorScore = this.getLastScore('superiorScore');
      this.lastSelfScore = this.getLastScore('selfScore')
      this.lastCenterScore = this.getLastScore('lastCenterScore')
    },
    onDeleteClick(index, operItemIndex) {
      if (index == 1) {
        this.model.aeeKpiAssessments.splice(operItemIndex, 1);
      } else if (index == 2) {
        this.model.aeeKpiAssessments.splice(operItemIndex + 1, 0, new Improtent(operItemIndex + 1));
      }
      //重新排序
      this.model.aeeKpiAssessments.forEach((item, index) => {
        item.index = index + 1;
      })
    },
    submitForm() {
      const that = this;
      const valid = this.validate();
      // 触发表单验证
      if (valid) {
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.$emit('ok');
          } else {
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
        })
      }

    },
    //自定义验证
    validate() {
      let flag = true;
      return flag;
    },
    //引用静态方法
    ...mapGetters(["nickname", "avatar", "userInfo"]),
    deleteImport(removeItemindex) {
      if (this.model.worktaskList.length > 3) {
        this.model.worktaskList.splice(removeItemindex, 1);
        //重新排序
        this.model.worktaskList.forEach((item, index) => {
          item.index = index + 1;
        })
      } else {
        this.$message.error("工作任务考核指标最少需要三项，不能删除")
      }

    },
    addLineImport() {
      this.model.worktaskList.push(new Improtent(this.model.worktaskList.length + 1)
      );
    },
    deleteAssess(removeItemIndex) {
      this.model.aeeKpiAssessments.splice(removeItemIndex, 1);
      //重新排序
      this.model.aeeKpiAssessments.forEach((item, index) => {
        item.index = index + 1;
      })

    },
    addLineAssess() {
      this.model.aeeKpiAssessments.push(new Assessments(this.model.aeeKpiAssessments.length + 1)
      );
    },
    blurNumFunc(e, type, index, attr) {
      //失去焦点实现双向数据绑定
      let content = e.target.innerText
      if (content == undefined || content === '') {
        return false;
      }
//判断是否是数字
      if (!this.isIntNum(content)) {
        e.target.innerText = '';
        this.$message.error("请输入数字");
        return false;
      }
      content = parseInt(content);
      if (type === 1) {
        if (content === 0 || content === 10) {
          this.model.worktaskList[index][attr] = content;
        } else {
          e.target.innerText = '';
          this.$message.error("评价分数只能是0或10");
        }
      } else {
        this.model.aeeKpiAssessments[index][attr] = content;
      }
      this.model.worktaskList.forEach((item, index) => {
        // item.index = index + 1;
      })
      console.log(this.model.worktaskList)

    },

    isIntNum(val) {
      console.log(val)
      var numReg = /^[0-9]*$/
      var numRe = new RegExp(numReg)
      if (numRe.test(val)) {
        return true;
      } else {
        return false;
      }

    },
    //根据传入的属性获取分数
    getLastScore(attr) {
      let score = 0;
      this.model.worktaskList.forEach(item => {
        if (item && item[attr]) {

          score += item[attr];
        }
      })
      this.model.aeeKpiAssessments.forEach(item => {
        if (item && item[attr]) {

          score += item[attr];
        }
      })
      return score;
    }
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';

table {
  th {
    width: 120px;
    height: 50px;
    line-height: 25px;
    padding: 5px;
  }

  td {
    font-weight: bold;
    text-align: center;
    height: 30px;
    line-height: 25px;
    padding: 5px;
  }

  th {
    text-align: center;
  }
}

.title_tr {
  font-weight: bold;
  text-align: center;
  height: 30px;
  line-height: 25px;
  padding: 5px;
}

.no_border {
  border: none;

}

.important_tr {
  min-height: 55px;
}

.assessment_tr {
  min-height: 100px;

}

.center_backgroud {
  background-color: #cda0a2;
}

.text_right {
  text-align: right;
}
</style>